﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DotNetOpenAuth.OAuth;
using MVCMongo.Filters;
using System.Xml;
using System.Collections;
using DotNetOpenAuth;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Web;

namespace MVCMongo.Filters
{
    public class GetYahooContacts
    {
        public string ConsumerKey
        {
            get
            {
                return "dj0yJmk9U3ZNRkpCaDY1YWNVJmQ9WVdrOU9VdFZZVkp6TkdzbWNHbzlOVGd4TWpJek16WXkmcz1jb25zdW1lcnNlY3JldCZ4PTQ1";
            }
        }
        public string ConsumerSecret
        {
            get
            {
                return "3def4599181acc5161fd372ecf6195246a708439";
            }
        }


        private string _ouathVerifier;
        public string OauthVerifier
        {
            get
            {
                try
                {
                    if (!string.IsNullOrEmpty(_ouathVerifier))
                        return _ouathVerifier;
                    else
                        return string.Empty;
                }
                catch
                {
                    return string.Empty;
                }
            }
            set
            {
                _ouathVerifier = value;
            }
        }

        private string _oauthToken;

        public string OauthToken
        {
            get
            {
                if (!string.IsNullOrEmpty(_oauthToken))
                    return _oauthToken;
                else
                    return string.Empty;
            }
            set
            {
                _oauthToken = value;
            }
        }

        private string _oauthTokenSecret;

        public string OauthTokenSecret
        {
            get
            {
                if (!string.IsNullOrEmpty(_oauthTokenSecret))
                    return _oauthTokenSecret;
                else
                    return string.Empty;
            }
            set
            {
                _oauthTokenSecret = value;
            }
        }

        private string _oauthSessionHandle;
        public string OauthSessionHandle
        {
            get
            {
                if (!string.IsNullOrEmpty(_oauthSessionHandle))
                    return _oauthSessionHandle;
                else
                    return string.Empty;
            }
            set
            {
                _oauthSessionHandle = value;
            }
        }

        private string _oauthYahooGuid;
        public string OauthYahooGuid
        {
            get
            {
                try
                {
                    if (!string.IsNullOrEmpty(_oauthYahooGuid))
                        return _oauthYahooGuid;
                    else
                        return string.Empty;
                }
                catch
                {
                    return string.Empty;
                }
            }
            set
            {
                _oauthYahooGuid = value;
            }
        }

        
        
        
        public string authorization(string returnUrl)
        {

            string authorizationUrl = string.Empty;
            authorizationUrl = GetRequestToken(returnUrl);
            return authorizationUrl;
            
        }

        public List<string> GetContacts()
        {
            GetAccessToken(OauthToken, OauthVerifier);
            return RetriveContacts();
        }



        private string GetRequestToken(string returnUrl)
        {
            string authorizationUrl = string.Empty;
            OAuthBase oauth = new OAuthBase();

            Uri uri = new Uri("https://api.login.yahoo.com/oauth/v2/get_request_token");
            string nonce = oauth.GenerateNonce();
            string timeStamp = oauth.GenerateTimeStamp();
            string normalizedUrl;
            string normalizedRequestParameters;
            string sig = oauth.GenerateSignature(uri, ConsumerKey, ConsumerSecret, string.Empty, string.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT, out normalizedUrl, out normalizedRequestParameters); //OAuthBase.SignatureTypes.HMACSHA1
            StringBuilder sbRequestToken = new StringBuilder(uri.ToString());
            sbRequestToken.AppendFormat("?oauth_nonce={0}&", nonce);
            sbRequestToken.AppendFormat("oauth_timestamp={0}&", timeStamp);
            sbRequestToken.AppendFormat("oauth_consumer_key={0}&", ConsumerKey);
            sbRequestToken.AppendFormat("oauth_signature_method={0}&", "PLAINTEXT"); //HMAC-SHA1
            sbRequestToken.AppendFormat("oauth_signature={0}&", sig);
            sbRequestToken.AppendFormat("oauth_version={0}&", "1.0");
            sbRequestToken.AppendFormat("oauth_callback={0}", HttpUtility.UrlEncode(returnUrl));
            //Response.Write(sbRequestToken.ToString());
            //Response.End();

            try
            {
                string returnStr = string.Empty;
                string[] returnData;

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sbRequestToken.ToString());
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader streamReader = new StreamReader(res.GetResponseStream());
                returnStr = streamReader.ReadToEnd();
                returnData = returnStr.Split(new Char[] { '&' });
                //Response.Write(returnStr);

                int index;
                if (returnData.Length > 0)
                {
                    //index = returnData[0].IndexOf("=");
                    //string oauth_token = returnData[0].Substring(index + 1);
                    //Session["Oauth_Token"] = oauth_token;

                    index = returnData[1].IndexOf("=");
                    string oauth_token_secret = returnData[1].Substring(index + 1);
                    OauthTokenSecret = oauth_token_secret;

                    //index = returnData[2].IndexOf("=");
                    //int oauth_expires_in;
                    //Int32.TryParse(returnData[2].Substring(index + 1), out oauth_expires_in);
                    //Session["Oauth_Expires_In"] = oauth_expires_in;

                    index = returnData[3].IndexOf("=");
                    string oauth_request_auth_url = returnData[3].Substring(index + 1);
                    authorizationUrl = HttpUtility.UrlDecode(oauth_request_auth_url);
                }
            }
            catch (WebException ex)
            {
                //Response.Write(ex.Message);
            }
            return authorizationUrl;
        }

        private void GetAccessToken(string oauth_token, string oauth_verifier)
        {
            OAuthBase oauth = new OAuthBase();

            Uri uri = new Uri("https://api.login.yahoo.com/oauth/v2/get_token");
            string nonce = oauth.GenerateNonce();
            string timeStamp = oauth.GenerateTimeStamp();
            string sig = ConsumerSecret + "%26" + OauthTokenSecret;

            StringBuilder sbAccessToken = new StringBuilder(uri.ToString());
            sbAccessToken.AppendFormat("?oauth_consumer_key={0}&", ConsumerKey);
            sbAccessToken.AppendFormat("oauth_signature_method={0}&", "PLAINTEXT"); //HMAC-SHA1
            sbAccessToken.AppendFormat("oauth_signature={0}&", sig);
            sbAccessToken.AppendFormat("oauth_timestamp={0}&", timeStamp);
            sbAccessToken.AppendFormat("oauth_version={0}&", "1.0");
            sbAccessToken.AppendFormat("oauth_token={0}&", oauth_token);
            sbAccessToken.AppendFormat("oauth_nonce={0}&", nonce);
            sbAccessToken.AppendFormat("oauth_verifier={0}", oauth_verifier);
            //Response.Write(sbAccessToken.ToString());
            //Response.End();

            try
            {
                string returnStr = string.Empty;
                string[] returnData;

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sbAccessToken.ToString());
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader streamReader = new StreamReader(res.GetResponseStream());
                returnStr = streamReader.ReadToEnd();
                returnData = returnStr.Split(new Char[] { '&' });
                //Response.Write(returnStr);
                //Response.End();

                int index;
                if (returnData.Length > 0)
                {
                    index = returnData[0].IndexOf("=");
                    OauthToken = returnData[0].Substring(index + 1);

                    index = returnData[1].IndexOf("=");
                    string oauth_token_secret = returnData[1].Substring(index + 1);
                    OauthTokenSecret = oauth_token_secret;

                    //index = returnData[2].IndexOf("=");
                    //int oauth_expires_in;
                    //Int32.TryParse(returnData[2].Substring(index + 1), out oauth_expires_in);

                    index = returnData[3].IndexOf("=");
                    string oauth_session_handle = returnData[3].Substring(index + 1);
                    OauthSessionHandle = oauth_session_handle;

                    //index = returnData[4].IndexOf("=");
                    //int oauth_authorization_expires_in;
                    //Int32.TryParse(returnData[4].Substring(index + 1), out oauth_authorization_expires_in);

                    index = returnData[5].IndexOf("=");
                    string xoauth_yahoo_guid = returnData[5].Substring(index + 1);
                    OauthYahooGuid = xoauth_yahoo_guid;
                }
            }
            catch (WebException ex)
            {

                //Response.Write(ex.Message);
            }
        }

        private List<string> RetriveContacts()
        {
            OAuthBase oauth = new OAuthBase();

            Uri uri = new Uri("http://social.yahooapis.com/v1/user/" + OauthYahooGuid + "/contacts?format=XML");
            string nonce = oauth.GenerateNonce();
            string timeStamp = oauth.GenerateTimeStamp();
            string normalizedUrl;
            string normalizedRequestParameters;
            string sig = oauth.GenerateSignature(uri, ConsumerKey, ConsumerSecret, OauthToken, OauthTokenSecret, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);

            StringBuilder sbGetContacts = new StringBuilder(uri.ToString());

            //Response.Write("URL: " + sbGetContacts.ToString());
            //Response.End();

            try
            {
                string returnStr = string.Empty;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sbGetContacts.ToString());
                req.Method = "GET";

                string authHeader = "Authorization: OAuth " +
                "realm=\"yahooapis.com\"" +
                ",oauth_consumer_key=\"" + ConsumerKey + "\"" +
                ",oauth_nonce=\"" + nonce + "\"" +
                ",oauth_signature_method=\"HMAC-SHA1\"" +
                ",oauth_timestamp=\"" + timeStamp + "\"" +
                ",oauth_token=\"" + OauthToken + "\"" +
                ",oauth_version=\"1.0\"" +
                ",oauth_signature=\"" + HttpUtility.UrlEncode(sig) + "\"";

                //Response.Write("</br>Headers: " + authHeader);

                req.Headers.Add(authHeader);

                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader streamReader = new StreamReader(res.GetResponseStream());
                returnStr = streamReader.ReadToEnd();
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(returnStr);
                XmlNodeList elemList = xmldoc.DocumentElement.GetElementsByTagName("fields");

                List<string> emails = new List<string>();
                for (int i = 0; i < elemList.Count; i++)
                {
                    if (elemList[i].ChildNodes[1].InnerText == "email")
                        emails.Add(elemList[i].ChildNodes[2].InnerText);
                    //Response.Write(elemList[i].ChildNodes[2].InnerText + "<br/>");
                }
                return emails;
                
            }

            catch (WebException ex)
            {
                return null;
            }
        }

    }
}
